package heven.holt.wan.android.loading.delegate

import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import heven.holt.library.loading.LoadingStateView
import heven.holt.wan.android.databinding.LayoutTitleSearchBinding
import heven.holt.wan.android.model.HotKeyModel
import javax.inject.Inject

class SearchHeaderViewDelegate @Inject constructor() : LoadingStateView.ViewDelegate<LoadingStateView.ViewHolder>(),
    DefaultLifecycleObserver {
    private lateinit var binding: LayoutTitleSearchBinding

    private var hotKeys: List<HotKeyModel>? = null
    private var position = 0

    override fun onCreateViewHolder(
        inflater: LayoutInflater,
        parent: ViewGroup
    ): LoadingStateView.ViewHolder {
        binding = LayoutTitleSearchBinding.inflate(inflater, parent, false)
        return LoadingStateView.ViewHolder(binding.root)
    }

    override fun onBindViewHolder(holder: LoadingStateView.ViewHolder) {
        binding.hotKey.setFactory {
            TextView(binding.hotKey.context).apply {
                setTextColor(Color.WHITE)
                textSize = 12f
            }
        }
    }

    private val action = Runnable {
        updateSwitchText()
        startTimber()
    }

    private fun updateSwitchText() {
        if (!hotKeys.isNullOrEmpty())
            binding.hotKey.setText(hotKeys!![position++ % hotKeys!!.size].name)
    }

    fun bindHotKeys(hotKeys: List<HotKeyModel>) {
        this.hotKeys = hotKeys
        updateSwitchText()
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        stopTimber()
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        startTimber()
    }

    private fun startTimber() {
        binding.hotKey.postDelayed(action, 5000)
    }

    private fun stopTimber() {
        binding.hotKey.removeCallbacks(action)
    }
}